package com.dd.lnetwork.exception

import android.text.TextUtils
import android.util.Log
import com.dd.lnetwork.exception.ErrorMessage.session_overdue_tip
import com.google.gson.JsonParseException
import org.json.JSONException
import retrofit2.HttpException
import java.io.IOException
import java.net.ConnectException
import javax.net.ssl.SSLHandshakeException

object ExceptionNetWork {
    private val CODE_400 = 400
    private val UNAUTHORIZED = 401
    private val FORBIDDEN = 403
    private val NOT_FOUND = 404
    private val REQUEST_TIMEOUT = 408
    private val INTERNAL_SERVER_ERROR = 500
    private val BAD_GATEWAY = 502
    private val SERVICE_UNAVAILABLE = 503
    private val GATEWAY_TIMEOUT = 504

    fun handleException(e: Throwable): ResponseThrowable {
        val ex: ResponseThrowable
        return when (e) {
            is HttpException -> {
                var string = "Code:"
                string = "$string${e.code()} "
                e.response()?.let {
                    var request= it.raw().toString()
                    string = ("${string}Body:${request} ")
                }

                if (!e.message.isNullOrEmpty()) {
                    string = ("${string}Message:${e.message()} ")
                }

                Log.e(
                    "ExceptionNetWork",
                    e.code().toString() + "------" + e.message
                )

                var code = ERROR.HTTP_ERROR
                var msg = ""
                when (e.code()) {
                    UNAUTHORIZED -> {
                        code = UNAUTHORIZED
                        msg = session_overdue_tip
                    }

                    FORBIDDEN -> msg = ErrorMessage.deny_access
                    NOT_FOUND -> msg = ErrorMessage.access_resource_not_exist
                    REQUEST_TIMEOUT -> msg = ErrorMessage.connect_fail
                    INTERNAL_SERVER_ERROR,
                    BAD_GATEWAY,
                    SERVICE_UNAVAILABLE, GATEWAY_TIMEOUT -> msg =
                        ErrorMessage.server_busy_try_again

                    CODE_400 -> msg = try {
                        var response = e.response()?.let {
                            it.errorBody().toString()
                        }
                        response?.let {
                            ErrorMessage.data_exception
                        } ?: ""
                    } catch (e1: IOException) {
                        e1.printStackTrace()
                        ErrorMessage.data_exception
                    } catch (e2: Exception) {
                        e2.printStackTrace()
                        ErrorMessage.data_exception
                    }

                    else -> msg = ErrorMessage.data_exception
                }
                ex = ResponseThrowable(e, code)
                ex.message = msg
                ex
            }

            is ServerException -> {
                val resultException: ServerException = e
                Log.e("ExceptionNetWork", "------${resultException.message}")
                ex = ResponseThrowable(e, ERROR.UNKNOWN)
                ex.message = resultException.message
                ex
            }

            is JsonParseException, is JSONException -> {
                ex = ResponseThrowable(e, ERROR.PARSE_ERROR)
                ex.message = ErrorMessage.data_exception
                ex
            }

            is ConnectException -> {
                ex = ResponseThrowable(e, ERROR.NETWORK_ERROR)
                ex.message = ErrorMessage.connect_fail
                ex
            }

            is SSLHandshakeException -> {
                ex = ResponseThrowable(e, ERROR.SSL_ERROR)
                ex.message = ErrorMessage.certificate_validation_failed
                ex
            }

            else -> {
                ex = ResponseThrowable(e, ERROR.UNKNOWN)
                ex.message = ErrorMessage.connect_fail
                if (!TextUtils.isEmpty(e.message)) {
                    Log.e("ExceptionNetWork", "------${e.message}")
                }
                ex
            }
        }
    }
}

object ERROR {
    /**
     * 未知错误
     */
    const val UNKNOWN = 1000

    /**
     * 解析错误
     */
    const val PARSE_ERROR = 1001

    /**
     * 网络错误
     */
    const val NETWORK_ERROR = 1002

    /**
     * 协议出错
     */
    const val HTTP_ERROR = 1003

    /**
     * 证书出错
     */
    const val SSL_ERROR = 1005

    /**
     * 数据错误
     */
    const val ERROR_DATA = 2112

    /**
     * 未知错误
     */
    const val ERROR_UN_KNOW = 2113

    /**
     * 未登陆
     */
    const val ERROR_UN_LOGIN = 2114

    /**
     * 服务器返回错误
     */
    const val ERROR_API = 2115

    /**
     * 自定义错误
     */
    const val CUSTOMER_ERROR = 2116
}

object ErrorMessage {
    const val session_overdue_tip = "用户会话过期，请重新登录！"
    const val deny_access = "拒绝访问！"
    const val access_resource_not_exist = "请求资源不存在！"
    const val server_busy_try_again = "服务器繁忙,请稍后重试"
    const val data_exception = "数据异常"
    const val connect_fail = "连接失败"
    const val certificate_validation_failed = "证书验证失败"
}